import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

public class Demo01_DriverManager {
    public static void main(String[] args)  {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //数据库连接
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8" +
                    "&allowPublicKeyRetrieval=true&useSSL=false", "root", "123456");
            statement = connection.createStatement();
            //执行SQL
            System.out.println("请输入想要查找的姓名:");
            Scanner scanner = new Scanner(System.in);
            String name = scanner.next();
            String sql = "select id, name, chinese, math, english from exam where name = '"+ name +"'";
            //获取执行结果
            resultSet = statement.executeQuery(sql);
            //遍历结果
            while(resultSet.next()){
                long id = resultSet.getLong(1);
                String Stu_name = resultSet.getString(2);
                double chinese = resultSet.getDouble(3);
                double math = resultSet.getDouble(4);
                double english = resultSet.getDouble(5);
                System.out.println(MessageFormat.format("学生编号={0}, 学生姓名={1}, 语文成绩={3}, 数学成绩={4}, 英语成绩={5}", id, Stu_name,
                        chinese, math, english));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            if(connection != null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(statement != null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(resultSet != null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}